const http = require('http');
const https = require('https');
const assert = require('assert');
const urllib = require('url')

function requestUrl(url, headers) {
    // url.parse会自动解析出一段url的信息，其中就包含host、path
    let urlObj = urllib.parse(url);
    let httpMod = null;

    if (urlObj.protocol == 'http:') {
        httpMod = http;
    } else if (urlObj.protocol == 'https:') {
        httpMod = https;
    } else {
        throw new Error('协议无法识别');
    }

    return new Promise((resolve, reject) => {

        let req = httpMod.request({
            host: urlObj.host,
            path: urlObj.path,
            headers,
        }, (res) => {
            console.log('得到了服务器的响应');
            if (res.statusCode >= 200 && res.statusCode < 300 || res.statusCode == 304) {
                let arr = [];
                res.on('data', (data) => {
                    arr.push(data);
                })
                res.on('end', () => {
                    let buffer = Buffer.concat(arr);
                    // 正常接收完数据，成功回调，状态码就简单统一返回200
                    resolve({
                        status: 200,
                        body: buffer,
                        headers: res.headers
                    })
                })
            } else if (res.statusCode == 301 || res.statusCode == 302) {
                // 成功请求到了服务器，也属于成功回调，只是数据没有请求到
                resolve({
                    status: res.statusCode,
                    body: null,
                    headers: res.headers
                })
            } else {
                // 真正的请求错误
                reject({
                    status: res.statusCode,
                    body: null,
                    headers: res.headers
                })
            }
        })

        req.on('error', (err) => {
            console.log(err);
        })

        req.write('');
        req.end();
    })
}


module.exports = async function request(url, reqHeaders) {
    try {
        while(1) {
            let {status, body, headers} = await requestUrl(url);
            // console.log(status, body, headers);
            if (status == 200) {
                return {status, body, headers};
            } else {
                assert(status == 301 || status == 302);
                assert(headers.location);
                url = headers.location;
            }
        }
    } catch(e) {
        console.log(e);
    }
}



// (async () => {
    // let {status, body, headers} = await request('https://shouji.tmall.com/');
    //
    // fs.writeFile(pathlib.resolve('tmp', 'shouji_tmall.html'), body, (err) => {
    //     if (err) {
    //         console.log('写入失败');
    //     } else {
    //         console.log('写入成功');
    //     }
    // })
// })()
